package cn.edu.xmist.java.util.arraylist;

import java.lang.reflect.Field;
import java.util.ArrayList;

/**
 * @author zhongjinbin 2021/4/9
 * @since 0.0.1
 * ArrayList的扩容demo
 */
public class ArrayListGrowDemo {
    // 获取list容量
    public static Integer getCapacity(ArrayList list) {
        Integer length = null;
        Class clazz = list.getClass();
        Field field;
        try {
            field = clazz.getDeclaredField("elementData");
            field.setAccessible(true);
            Object[] object = (Object[]) field.get(list);
            length = object.length;
            return length;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return length;
    }

    public static void main(String[] args) {
        ArrayList<Integer> list1 = new ArrayList<>();

        /**
         * 获取默认初始容量10
         */
        Integer capacity = getCapacity(list1);
        int size = list1.size();
        System.out.println("list1的容量:" + capacity);
        System.out.println("list1的大小:" + size);
        System.out.println("----------------------------");

        ArrayList<Integer> list2 = new ArrayList<>(11);

        /**
         * 获取容量,arraylist初始化容量是11
         */
        capacity = getCapacity(list2);
        list2.add(1);
        size = list2.size();
        System.out.println("list2的初始容量:" + capacity);
        System.out.println("list2的大小:" + size);
        System.out.println("----------------------------");

        ArrayList<Integer> list3 = new ArrayList<>(11);

        /**
         * 获取容量,arraylist初始化容量是10
         */
        capacity = getCapacity(list3);
        System.out.println("list3的初始容量:" + capacity);
        for (int i = 0; i < 12; i++) {
            list3.add(i);
        }
        capacity = getCapacity(list3);
        size = list3.size();
        System.out.println("list3的扩容容量:" + capacity);
        System.out.println("list3的大小:" + size);
        System.out.println("----------------------------");

        ArrayList<Integer> list4 = new ArrayList<>(11);
        for (int i = 0; i < 12; i++) {
            list4.add(i);
        }
        capacity = getCapacity(list4);
        System.out.println("list4的初始容量:" + capacity);
        size = list4.size();
        System.out.println("list4的扩容容量:" + capacity);
        System.out.println("list4的大小:" + size);
        list4.remove(list4.size() - 1);
        capacity = getCapacity(list4);
        System.out.println("list4的缩容容量:" + capacity);
        System.out.println("list4的大小:" + size);
    }
}
